package com.feihao.zhou.web.controller.story;

import com.feihao.zhou.bean.story.Question;
import com.feihao.zhou.bean.story.QuestionItem;
import com.feihao.zhou.service.story.QuestionItemService;
import com.feihao.zhou.service.story.Impl.QuestionItemServiceImpl;
import com.feihao.zhou.utils.BeanUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;


@WebServlet("/store/questionItem")
public class QuestionItemServlet extends HttpServlet {
    static QuestionItemService questionItemService = new QuestionItemServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text.html;charset=utf-8");

        //获取请求option：
        String operation = req.getParameter("operation");
        if ("list".equals(operation)){
            //查询方法：
            findAll(req,resp);
        }else if ("save".equals(operation)){
            try {
                save(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toEdit".equals(operation)){
            toEdit(req,resp);
        }else if ("update".equals(operation)){
            try {
                update(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("delete".equals(operation)){
            delete(req,resp);
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {

       /*这是针对没有文件上传修改的代码：
       QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class);
        questionItemService.update(questionItem);

        String questionId = req.getParameter("questionId");
        req.setAttribute("questionId",questionId);
        //重定向：
        findAll(req,resp);*/

        String questionId = null;
        //判断操作是否支持文件上传操作：
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建文件磁盘工厂对象：
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //servlet文件上传核心对象：
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //从request中读取数据：
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //获取questionId:!!!!!!   有点冒险，不确定哪个是questionId值！摸索出来的，前端提交顺序改变的话就完了！！！
            questionId = fileItems.get(0).getString();
            System.out.println(questionId);

            boolean flag = false;
            //给定标记为，看是否有上传文件：
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())) {
                    //非空，则有东西：
                    flag = true;
                }
            }


            //处理普通数据：
            QuestionItem questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);
            System.out.println(questionItem);
            //给业务层传递标记：true则添加id，false 则不添加
            questionItemService.update(questionItem, flag);

            //处理文件：
            for (FileItem fileItem : fileItems) {
//                System.out.println(fileItem);
                //判断是否是文件：    假如没有上传文件，默认是空
                if (!fileItem.isFormField() && fileItem.getSize() != 0) {
                    //是文件字段：写道指定位置：
                    fileItem.write(new File(req.getServletContext().getRealPath("itemUpload"), questionItem.getPicture()));
                }

            }
            //设置到session域中
//            req.getSession().setAttribute("questionId", questionId);
//            req.getSession().setAttribute("questionItemId", questionItem.getId());
            //zhuangfa:
            findAll(req, resp, questionId);

        }
    }


    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        questionItemService.delete(id);

        //再次调用查询全部，展示在list.jsp页面
        String questionId = req.getParameter("questionId");
        findAll(req,resp);

    }


    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String questionId = req.getParameter("questionId");
        QuestionItem questionItem = questionItemService.findById(id);
        req.setAttribute("questionItem",questionItem);
        req.setAttribute("questionId",questionId);
        //保存一个操作类型，传递前端进行判断操作：
        req.setAttribute("operation","update");

//        req.getRequestDispatcher(req.getContextPath()+"/WEB-INF/store/questionItem/list.jsp").forward(req,resp);
        findAll(req,resp);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        /*String questionId = req.getParameter("questionId");*/
        /*QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class);
        questionItemService.save(questionItem,questionId);
        //
        findAll(req,resp);*/
        String questionId = null;
        //判断操作是否支持文件上传操作：
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建文件磁盘工厂对象：
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //servlet文件上传核心对象：
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //从request中读取数据：
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //获取questionId:!!!!!!
             questionId= fileItems.get(0).getString();
            System.out.println(questionId);

            boolean flag = false;
            //给定标记为，看是否有上传文件：
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())) {
                    //非空，则有东西：
                    flag = true;
                }
            }


            //处理普通数据：
            QuestionItem questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);
            System.out.println(questionItem);
            //给业务层传递标记：true则添加id，false 则不添加
            questionItemService.save(questionItem, questionId, flag);

            //处理文件：
            for (FileItem fileItem : fileItems) {
//                System.out.println(fileItem);
                //判断是否是文件：    假如没有上传文件，默认是空
                if (!fileItem.isFormField() && fileItem.getSize() != 0) {
                    //是文件字段：写道指定位置：
                    fileItem.write(new File(req.getServletContext().getRealPath("itemUpload"), questionItem.getPicture()));
                }

            }
            //设置到session域中
//            req.getSession().setAttribute("questionId", questionId);
//            req.getSession().setAttribute("questionItemId", questionItem.getId());
            //zhuangfa:
            findAll(req, resp,questionId);

//            resp.sendRedirect(req.getContextPath() + "/store/question?operation=list");


        }
    }


    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先定义page,pageSize:
        int page = 1;
        int pageSize = 5;

        String questionId = req.getParameter("questionId");

        if(StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }

        //调用业务层方法查询所有：
        PageInfo all = questionItemService.findAll(questionId,page, pageSize);

        System.out.println(all);
        //查询是为前端提供问题的id
        req.setAttribute("questionId",questionId);
        req.setAttribute("page",all);


        if (req.getAttribute("operation")==null) {
            //保存一个操作传递前端：
            req.setAttribute("operation", "save");
        }
        req.getRequestDispatcher("/WEB-INF/store/questionItem/list.jsp").forward(req,resp);
    }

    //针对提交文件的form表单，再次调用findAll方法，获取不到questionId，添加此方法：（重载添加questionId形式参数）
    private void findAll(HttpServletRequest req, HttpServletResponse resp,String questionId) throws ServletException, IOException {
        //首先定义page,pageSize:
        int page = 1;
        int pageSize = 5;

//        String questionId = req.getParameter("questionId");

        if(StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }

        //调用业务层方法查询所有：
        PageInfo all = questionItemService.findAll(questionId,page, pageSize);

        System.out.println(all);
        //查询是为前端提供问题的id
        req.setAttribute("questionId",questionId);
        req.setAttribute("page",all);


        if (req.getAttribute("operation")==null) {
            //保存一个操作传递前端：
            req.setAttribute("operation", "save");
        }
        req.getRequestDispatcher("/WEB-INF/store/questionItem/list.jsp").forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
